import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import menuList from '@/json/menu.json'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/index.vue'),
    },
  ],
})

router.beforeEach((to, from, next) => {
  const whiteList = ['/login']
  const userInfo = localStorage.getItem('userInfo')
  const token = userInfo ? JSON.parse(userInfo).token : null
  if (to.path === '/login' && token) {
    next('/home')
    return
  }
  if (whiteList.includes(to.path)) {
    // 否则允许访问
    next()
    return
  } else {
    if (token) {
      next()
      return
    } else {
      next('/login')
    }
  }
})

const layoutcomponents = import.meta.glob('../views/layout/**/*.vue')

// 初始化动态路由（例如在登录后调用）
function generateRoute(menu: any) {
  return {
    path: menu.path,
    name: menu.name,
    component: () => layoutcomponents[`../views/layout${menu.path}/index.vue`](),
    meta: { permission: menu.permission },
  }
}

export const addDynamicRoutes = () => {
  // 过滤出用户有权限的菜单
  const userInfo: any = localStorage.getItem('userInfo')
  const userInfoObj = userInfo ? JSON.parse(userInfo) : null
  const filteredMenus = menuList.menus.filter((item) => {
    if (item.permission === null) return true
    return userInfoObj?.permissions.includes(item.permission) || false
  })

  // 生成路由对象数组
  const routes = filteredMenus.map((menu) => {
    return generateRoute(menu)
  })

  console.log(routes, 'routes路由菜单')

  const layoutRoute = {
    path: '/layout',
    name: 'layout',
    component: () => import('../views/layout/index.vue'),
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('../views/layout/indexs/index.vue'),
      },
      ...routes,
    ],
  }
  router.addRoute(layoutRoute)
}

export default router
